<%@ page contentType="text/html; charset=ISO-8859-1"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.*"%>
<%@ page import="java.net.*"%>
<%@ page import="org.mapfish.geo.*"%>
<%@ page import="org.json.*"%>
<%@ page import="it.eng.spagobi.services.proxy.*"%>
<%@ page import="it.eng.spagobi.services.dataset.bo.*"%>
<%@ page import="it.eng.spagobi.tools.dataset.bo.*"%>
<%@ page import="it.eng.spagobi.tools.dataset.common.datastore.*"%>
<%
/*
 * This software is provided under the terms
 * of GNU Lesser GPL License. You may not use
 * this file except in compliance with the license. If you need a copy of the license,
 * please go to http://www.gnu.org/copyleft/lesser.html. 
 * This code uses the SpagoBI 2.2 SDK. 
 
 * @author Fabio D'Ovidio
 * @author Matteo Villari
 
*/
String user = request.getParameter("userID");
String label = request.getParameter("label");
String geoserverUrl = request.getParameter("server");
String pos = request.getParameter("businessId");
String layer = request.getParameter("layer");
String id = request.getParameter("geoid");

//DataSet
DataSetServiceProxy datasetProxy = new DataSetServiceProxy(user, request.getSession());
IDataSet dataSet =  datasetProxy.getDataSetByLabel(label);
try {
		dataSet.loadData();
	} catch (Exception e) {
		e.printStackTrace();
	} 

//Datastore 
IDataStore dataStore = dataSet.getDataStore();
IDataStoreMetaData dataStoreMeta = dataStore.getMetaData();
      
// # COL NUMBER
int nc = dataStoreMeta.getFieldCount();

//Instantiate GeoJsonFactory
      MfGeoFactory geoFactory = new MfGeoFactory() {
          public MfFeature createFeature(final String id, final MfGeometry geometry, final JSONObject properties) {
              return new MfFeature() {
                  public String getFeatureId() {
                      return id;
                  }
                  public MfGeometry getMfGeometry() {
                      return geometry;
                  }
                  public void toJSON(JSONWriter builder) throws JSONException {
                      Iterator iter = properties.keys();
                      while (iter.hasNext()){
                    	  String key = (String) iter.next();
                    	  Object value = properties.get(key);
                    	  builder.key(key).value(value);                    	  
                      }
                  }
          };
      }
      };
      //Create Output Collection of Features
      Collection outputFeatureCollection = new ArrayList();
      //Reads GeoJSON from GeoServer
      MfGeoJSONReader jsonReader = new MfGeoJSONReader(geoFactory); 

// for each row
        Iterator it = dataStore.iterator();

        while(it.hasNext()) {
        
        IRecord record = (IRecord)it.next();
        IField field;
	      field = record.getFieldAt( dataStoreMeta.getFieldIndex(pos) );
        
	      
        
        //IDfetaure
        String idFeature = "" + field.getValue();

    
        //Prepare wfsUrl to get feature from GeoServer filtering by "idFeature"  
        String wfsUrl = "http://"+ geoserverUrl + "/geoserver/wfs?request=GetFeature&typename=topp:" + layer + "&Filter=<Filter><PropertyIsEqualTo><PropertyName>"+ id +"</PropertyName><Literal>"+ idFeature +"</Literal></PropertyIsEqualTo></Filter>&outputformat=json&version=1.0.0";
    
        
		String result = null;
        // geoserver call
    try
    {
    	URL url = new URL(wfsUrl);
        URLConnection conn = url.openConnection ();
        // Get the response
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = rd.readLine()) != null)
        {
        sb.append(line);        
        }
        rd.close();
        result = sb.toString();
               
        
        //featureCollection from GeoServer
        MfFeatureCollection featureCollection = (MfFeatureCollection) jsonReader.decode(result);
        List featureList = new ArrayList(featureCollection.getCollection());
        MfFeature feature = (MfFeature) featureList.get(0);
        
        //Geometry from GeoServer
        MfGeometry geom = feature.getMfGeometry();
        
        
        // JSON creation
        JSONObject jsonProperties = new JSONObject();
		
        //for each col
        for(int j=0; j<nc; j++){
        // fetch business data   
        
        if (dataStoreMeta.getFieldMeta(j).getType().equals(String.class) ){        
        jsonProperties.accumulate(dataStoreMeta.getFieldName(j), (String) record.getFieldAt( dataStoreMeta.getFieldIndex(dataStoreMeta.getFieldName(j)) ).getValue());  
        }
        if (dataStoreMeta.getFieldMeta(j).getType().equals(Integer.class) ){        
        jsonProperties.accumulate(dataStoreMeta.getFieldName(j), (Integer) record.getFieldAt( dataStoreMeta.getFieldIndex(dataStoreMeta.getFieldName(j)) ).getValue());  
        }
        if (dataStoreMeta.getFieldMeta(j).getType().equals(Float.class) ){        
        jsonProperties.accumulate(dataStoreMeta.getFieldName(j), (Float) record.getFieldAt( dataStoreMeta.getFieldIndex(dataStoreMeta.getFieldName(j)) ).getValue());  
        }
        if (dataStoreMeta.getFieldMeta(j).getType().equals(Double.class) ){        
        jsonProperties.accumulate(dataStoreMeta.getFieldName(j), (Double) record.getFieldAt( dataStoreMeta.getFieldIndex(dataStoreMeta.getFieldName(j)) ).getValue());  
        }
        if (dataStoreMeta.getFieldMeta(j).getType().equals(Long.class) ){        
        jsonProperties.accumulate(dataStoreMeta.getFieldName(j), (Long) record.getFieldAt( dataStoreMeta.getFieldIndex(dataStoreMeta.getFieldName(j)) ).getValue());  
        }
        if (dataStoreMeta.getFieldMeta(j).getType().equals(Short.class) ){        
        jsonProperties.accumulate(dataStoreMeta.getFieldName(j), (Short) record.getFieldAt( dataStoreMeta.getFieldIndex(dataStoreMeta.getFieldName(j)) ).getValue());  
        }

        }
        MfFeature featureToCollect = geoFactory.createFeature(idFeature,geom,jsonProperties);
        outputFeatureCollection.add(featureToCollect);
      } catch (Exception e)
      {
      e.printStackTrace();
      }
	}
	
    JSONStringer stringer = new JSONStringer();
    MfGeoJSONWriter builder = new MfGeoJSONWriter(stringer);
    builder.encodeFeatureCollection(new MfFeatureCollection(outputFeatureCollection));
    out.println(stringer);
%>